/*
 * Copyright By Peak3
 * Copyright By c336bf6ff03a756989bb456b5b5e3271228d43ed38461eb5cb5755d17a2fc9b8
 * All rights reserved.
 *
 * If you are not the intended user, you are hereby notified that any use, disclosure, copying, printing, forwarding or
 * dissemination of this property is strictly prohibited. If you have got this file in error, delete it from your system.
 */

package com.vv.tools.common.message;

import jakarta.servlet.http.HttpServletRequest;

import java.util.Objects;

import lombok.extern.slf4j.Slf4j;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author liwen
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice(basePackages = {"com.vv.tools"})
public class ExceptionBizHandler {

    /**
     * 自定义异常
     */
    @ExceptionHandler(CustomerBizException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<String> onIntentBizException(CustomerBizException exception) {
        ResultEnum result = exception.getResult();
        log.warn("CustomerBizException: {}", result.getCode(), exception);
        return Result.fail(result);
    }

    /**
     * 方法参数错误异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Object> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.error("方法参数错误异常");
        String message = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();
        return Result.fail(ResultEnum.VALID_EXCEPTION, message);
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public Result<Object> handleException(Exception e, HttpServletRequest request) {
        String requestUri = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常.", requestUri, e);
        return Result.fail(ResultEnum.EXCEPTION, e.getMessage());
    }

}
